import Vue from 'vue';
/*
 *  使用方法
 *  将以下代码复制到一个js文件中，然后在入口文件main.js中import引入即可；
 *  给elementUI的dialog上加上 v-dialogDrag 指令就可以实现弹窗的全屏和拉伸了。
 *  给dialog设置 :close-on-click-modal="false" , 禁止点击遮罩层关闭弹出层
 *  如果是form表单，不要将提交等按钮放置el-form-item，以免在上下拉伸时被隐藏
 */
// v-dialogDrag: 弹窗拖拽+水平方向伸缩
Vue.directive('dialogDrag', {
  bind(el, binding, vnode, oldVnode) {
    //弹框可拉伸最小宽高
    let minWidth = 400;
    let minHeight = 300;
    let maxHeight = binding.value.maxHeight;
    // 默认允许变幻大小
    let noResizeAble = binding.value.noResizeAble || false;
    //初始非全屏
    // 默认允许双击全屏
    let noFullScreen = binding.value.noFullScreen || false;
    let isFullScreen = false;
    //当前宽高
    let nowWidth = 0;
    let nowHight = 0;
    //当前顶部高度
    let nowMarginTop = 0;
    //获取弹框头部（这部分可双击全屏）
    const dialogHeaderEl = el.querySelector('.el-dialog__header');
    //弹窗
    const dragDom = el.querySelector('.el-dialog');
    //给弹窗加上overflow auto；不然缩小时框内的标签可能超出dialog；
    dragDom.style.overflow = "auto";
    //清除选择头部文字效果
    //dialogHeaderEl.onselectstart = new Function("return false");
    //头部加上可拖动cursor
    dialogHeaderEl.style.cursor = 'move';
    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
    let moveDown = (e) => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft;
      const disY = e.clientY - dialogHeaderEl.offsetTop;
      // 获取到的值带px 正则匹配替换
      let styL, styT;
      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (sty.left.includes('%')) {
        styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
        styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
      } else {
        styL = +sty.left.replace(/\px/g, '');
        styT = +sty.top.replace(/\px/g, '');
      };
      document.onmousemove = function(e) {
        // 通过事件委托，计算移动的距离
        const l = e.clientX - disX;
        const t = e.clientY - disY;
        // 移动当前元素 
        dragDom.style.left = `${l + styL}px`;
        dragDom.style.top = `${t + styT}px`;
        //将此时的位置传出去
        //binding.value({x:e.pageX,y:e.pageY})
      };
      document.onmouseup = function(e) {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
    dialogHeaderEl.onmousedown = moveDown;
    //双击头部全屏效果
    dialogHeaderEl.ondblclick = (e) => {
      if (noFullScreen) {
        return false;
      }
      if (isFullScreen == false) {
        nowHight = dragDom.clientHeight;
        nowWidth = dragDom.clientWidth;
        nowMarginTop = dragDom.style.marginTop;
        dragDom.style.left = 0;
        dragDom.style.top = 0;
        dragDom.style.height = "100VH";
        dragDom.style.width = "100VW";
        dragDom.style.marginTop = 0;
        isFullScreen = true;
        dialogHeaderEl.style.cursor = 'initial';
        dialogHeaderEl.onmousedown = null;
      } else {
        dragDom.style.height = "auto";
        dragDom.style.width = nowWidth + 'px';
        dragDom.style.marginTop = nowMarginTop;
        isFullScreen = false;
        dialogHeaderEl.style.cursor = 'move';
        dialogHeaderEl.onmousedown = moveDown;
      }
    }
    dragDom.onmousemove = function(e) {
      let moveE = e;
      if (e.clientX > dragDom.offsetLeft + dragDom.clientWidth - 10 || dragDom.offsetLeft + 10 > e.clientX) {
        if (!noResizeAble) {
          dragDom.style.cursor = 'w-resize';
        }
      } else if (el.scrollTop + e.clientY > dragDom.offsetTop + dragDom.clientHeight - 10) {
        if (!noResizeAble) {
          dragDom.style.cursor = 's-resize';
        }
      } else {
        dragDom.style.cursor = 'default';
        dragDom.onmousedown = null;
      }
      dragDom.onmousedown = (e) => {
        const clientX = e.clientX;
        const clientY = e.clientY;
        let elW = dragDom.clientWidth;
        let elH = dragDom.clientHeight;
        let EloffsetLeft = dragDom.offsetLeft;
        let EloffsetTop = dragDom.offsetTop;
        dragDom.style.userSelect = 'none';
        let ELscrollTop = el.scrollTop;
        //判断点击的位置是不是为头部
        if (clientX > EloffsetLeft && clientX < EloffsetLeft + elW && clientY > EloffsetTop && clientY < EloffsetTop + 100) {
          //如果是头部在此就不做任何动作，以上有绑定dialogHeaderEl.onmousedown = moveDown;
        } else {
          document.onmousemove = function(e) {
            if (noResizeAble) {
              return false;
            }
            e.preventDefault();
            // 移动时禁用默认事件
            //左侧鼠标拖拽位置
            if (clientX > EloffsetLeft && clientX < EloffsetLeft + 10) {
              //往左拖拽
              if (clientX > e.clientX) {
                dragDom.style.width = elW + (clientX - e.clientX) * 2 + 'px';
              }
              //往右拖拽
              if (clientX < e.clientX) {
                if (dragDom.clientWidth < minWidth) {} else {
                  dragDom.style.width = elW - (e.clientX - clientX) * 2 + 'px';
                }
              }
            }
            //右侧鼠标拖拽位置
            if (clientX > EloffsetLeft + elW - 10 && clientX < EloffsetLeft + elW) {
              //往左拖拽
              if (clientX > e.clientX) {
                if (dragDom.clientWidth < minWidth) {} else {
                  dragDom.style.width = elW - (clientX - e.clientX) * 2 + 'px';
                }
              }
              //往右拖拽
              if (clientX < e.clientX) {
                dragDom.style.width = elW + (e.clientX - clientX) * 2 + 'px';
              }
            }
            //底部鼠标拖拽位置
            if (ELscrollTop + clientY > EloffsetTop + elH - 20 && ELscrollTop + clientY < EloffsetTop + elH) {
              //往上拖拽
              if (clientY > e.clientY) {
                if (dragDom.clientHeight < minHeight) {} else {
                  dragDom.style.height = elH - (clientY - e.clientY) + 'px';
                  // 激发el-scroll调整
                  let _w = +sty.width.replace(/\px/g, '');
                  dragDom.style.width = (_w+0.1) + 'px';
                }
              }
              //往下拖拽
              if (clientY < e.clientY) {
                if (dragDom.clientHeight > maxHeight) {} else {
                  dragDom.style.height = elH - (clientY - e.clientY) + 'px';
                  let _w = +sty.width.replace(/\px/g, '');
                  dragDom.style.width = (_w+0.1) + 'px';
                }
              }
            }
            binding.value.resize(dragDom);
          };
          //拉伸结束
          document.onmouseup = function(e) {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        }
      }
    }
  },
  update(el, binding, vnode, oldVnode) {}
})

Vue.directive('clearNoNum', {
  bind(el, binding, vnode, oldVnode) {
    const _bindingValue = binding.value;
    let type = false;
    if(_bindingValue && _bindingValue.type)
      type = _bindingValue.type;
    const obj = el.querySelector('.el-input__inner') || el.querySelector('.cube-input-field');
    let zclearNoNum = function (e) {
      if(e.target.composing) return;
      if (type) {
        obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符  
        obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        if (type == '1') {
          obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3'); //只能输入一位小数
        } else if (type == '2') {
          obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3'); //只能输入两个小数
        } else if (type == '3') {
          obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d{3}).*$/, '$1$2.$3'); //只能输入三位小数
        }
        //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (obj.value.indexOf(".") < 0 && obj.value != "") {
          obj.value = parseFloat(obj.value);
        }
        //控制.开头的数字，如：.8798321
        // \.16513000.546
        if (obj.value && !obj.value.split(".")[0]) {
          obj.value = '0.' + (obj.value.split(".")[1] || '');
          zclearNoNum(e);
        }
        // 退格、删减不置0
        if (!obj.value && e.keyCode!==8 && e.keyCode!==46)
          obj.value = 0;
      } else {
        // 限制输入正整数
        obj.value = obj.value.replace(/[^\d]/g, "");
      }
      // 触发v-model的更新
      obj.dispatchEvent(new Event('input'));
    }

    let zblur = function (e) {
      zclearNoNum(e);
      setTimeout(()=>{
        if (obj.value && obj.value.indexOf(".") == obj.value.toString().length-1) {
          // 去除.结尾的情况
          obj.value = parseFloat(obj.value);
        }
        // 触发v-model的更新
        obj.dispatchEvent(new Event('change'));
      }, 50)
    }
    obj.onkeyup = zclearNoNum;
    obj.onblur = zblur;

    function onCompositionStart (e) {
      e.target.composing = true
    }
    
    function onCompositionEnd (e) {
      e.target.composing = false
      obj.dispatchEvent(new Event('input'));
    }
    // https://segmentfault.com/a/1190000009246058
    obj.addEventListener('compositionstart', onCompositionStart)
    obj.addEventListener('compositionend', onCompositionEnd)
  },
  update(el, binding, vnode, oldVnode) {}
})

Vue.directive('elDatesPicker', {
  bind(el, binding, vnode, oldVnode) {
    const obj = el.querySelector('.el-input__inner');
    let zinterval = null;

    obj.addEventListener('focus', ()=>{
      let _val = obj.value;
      if(_val && _val.split(',').length == 4){
        obj.value = '';
        vnode.context.$emit('zuidatespickerReset');
      }
      initInter();
    })

    function initInter () {
      zinterval = setInterval(()=>{
        let _val = obj.value;
        if(_val && _val.split(',').length == 4){
          setChoose();
        }
      }, 100)
    }

    function setChoose () {
      vnode.context.$emit('zuidatespickerChoose');
      clearInterval(zinterval);
      zinterval = null;
    }

    vnode.context.$on('hook:beforeDestroy', function () {
      if(zinterval){
        clearInterval(zinterval);
        zinterval = null;
      }
    });
  },
  update(el, binding, vnode, oldVnode) {}
})
